package com.jzqf.harmonydemo.base;

import ohos.agp.components.Component;
import ohos.agp.components.Text;
import ohos.agp.utils.Color;

import java.util.HashMap;

/**
 * 列表适配器ViewHolder封装
 *
 * @author LiuWeiHao
 * 2021/5/7 16:36
 */
public class BaseViewHolder {
    private HashMap<Integer, Component> mConponents;
    private Component mComponentItem;
    private ItemClickedListener itemClickedListener;

    public BaseViewHolder(Component componentItem) {
        this.mComponentItem = componentItem;
        mConponents = new HashMap<>();
    }

    public Component getComponent(int resId) {
        Component component = mConponents.get(resId);
        if (component == null) {
            component = mComponentItem.findComponentById(resId);
            mConponents.put(resId, component);
        }
        return component;
    }

    public void setText(int componentId, String message) {
        Text text = (Text) getComponent(componentId);
        text.setText(message);
    }

    public void setTextColor(int componentId, Color color) {
        Text text = (Text) getComponent(componentId);
        text.setTextColor(color);
    }

    public void setTextSize(int componentId, int size) {
        Text text = (Text) getComponent(componentId);
        text.setTextSize(size);
    }

    public void addClickedListener(int componentId) {
        getComponent(componentId).setClickedListener(component -> {
            if (itemClickedListener != null) {
                itemClickedListener.itemClick(componentId);
            }
        });
    }

    public void setItemClickedListener(ItemClickedListener itemClickedListener) {
        this.itemClickedListener = itemClickedListener;
    }

    public interface ItemClickedListener {
        void itemClick(int componentId);
    }
}
